package org.byteDance.l199;

import java.util.ArrayList;
import java.util.LinkedList;
import java.util.List;
import java.util.Queue;

/**
 * @Author yu
 * @Date 2022/3/5
 */
public class Solution {

    public static void main(String[] args) {

        TreeNode treeNode = new TreeNode(4);
        TreeNode treeNode1 = new TreeNode(5);
        TreeNode treeNode2 = new TreeNode(2, null, treeNode1);
        TreeNode treeNode3 = new TreeNode(3, null, treeNode);
        TreeNode treeNode4 = new TreeNode(1, treeNode2, treeNode3);

        Solution solution = new Solution();
        List<Integer> list = solution.rightSideView(treeNode4);
        System.out.println(list.toString());

    }

    /**
     * BFS
     *
     * @param root
     * @return java.util.List<java.lang.Integer>
     */
    public List<Integer> rightSideView(TreeNode root) {
        List<Integer> list = new ArrayList<>();
        if (root == null) {
            return list;
        }

        Queue<TreeNode> queue = new LinkedList<>();
        queue.add(root);

        while (!queue.isEmpty()) {

            // size 记录层节点个数
            int size = queue.size();
            while (size > 0) {
                TreeNode node = queue.poll();
                if (node.left != null) {
                    queue.add(node.left);
                }
                if (node.right != null) {
                    queue.add(node.right);
                }
                if (size - 1 == 0) {
                    list.add(node.val);
                }
                size--;
            }
        }

        return list;
    }

}

class TreeNode {
    int val;
    TreeNode left;
    TreeNode right;
    TreeNode() {}
    TreeNode(int val) { this.val = val; }
    TreeNode(int val, TreeNode left, TreeNode right) {
        this.val = val;
        this.left = left;
        this.right = right;
    }
}